import React from 'react';
import { Button, Dropdown, Form, Input, Menu } from 'antd';

interface ObjectType {
  [index: string]: any;
}

interface BaseInputState {
  readonly buttonText: string;
  readonly getFieldDecoratorId: string;
}

export class BaseInput extends React.Component<ObjectType, BaseInputState> {
  constructor(props: ObjectType) {
    super(props);
    this.state = {
      buttonText: props.buttonText,
      getFieldDecoratorId: props.getFieldDecoratorId,
    };
  }

  menu = () => (
    <Menu onClick={this.handleClick}>
      {this.props.menuData.map((val: ObjectType) => (
        <Menu.Item key={val.id}>{val.text}</Menu.Item>
      ))}
    </Menu>
  );

  /*
   * 点击按钮下拉菜单的时候改变当前按钮的名称
   * */
  handleClick = (e: ObjectType) => {
    const { menuData, needChangeId, changeMenuClick } = this.props;
    const current = menuData.find((val: ObjectType) => val.id === e.key * 1 || val.id === e.key);

    if (needChangeId) {
      this.setState({
        buttonText: current.text,
        getFieldDecoratorId: e.key,
      });
    } else {
      this.setState({
        buttonText: current.text,
      });
    }

    if (typeof changeMenuClick === 'function') changeMenuClick(current.text);
  };

  render() {
    const {
      getFieldDecorator,
      trigger,
      placeholder = '请输入',
      autoComplete = 'off',
      labelCol,
      wrapperCol,
      label,
      dropDownLabel,
      rules,
    } = this.props;

    const { buttonText, getFieldDecoratorId } = this.state;
    const currentLabel = dropDownLabel ? (
      <Dropdown overlay={this.menu} trigger={trigger}>
        <Button>{buttonText}</Button>
      </Dropdown>
    ) : (
      label
    );

    return (
      <Form.Item label={currentLabel} labelCol={labelCol} wrapperCol={wrapperCol}>
        {getFieldDecorator(getFieldDecoratorId, {
          rules,
        })(<Input placeholder={placeholder} autoComplete={autoComplete} />)}
      </Form.Item>
    );
  }
}
